const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
const webpack = require("webpack");
const {getStyleLoaders,splitChunks,getUrlLoader,tsLoader} = require("./utils");
let isDev = process.env.NODE_ENV == "development" ? true : false;
const {distPath} = require("./config");

module.exports = function(options) {
  let {
    libraryName = "lib_", //不要取去掉【lib_】dev-server的express会根据路径取值
    distPath = distPath, //打包工程输出根目录
    libraryPath = path.resolve(distPath, libraryName),//打包lib输出目录
    publicPath= "",
    dllPath = path.resolve(distPath, "dll"),//dll路径
    entryPath = "",//入口文件路径
    moduleRegex = /node_modules/,//排除不编译的模块路径
    isMiniStats = true, // webpack日志简化
    isAnalyzeBundle = false,// bundle依赖分析
    isShowTime=true,// 显示打包分析时长
  } = options;

  const config = {
    entry: {
      index: entryPath
    },
    output: {
      path: libraryPath,
      filename: "[name].js",
      chunkFilename:isDev?"[name].js":"[name].[contenthash:8].js",
      library: libraryName,
      libraryTarget: "umd",
      libraryExport: "default",
      globalObject: "this",
      publicPath: publicPath
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "../"),
        "~": distPath,
      },
      extensions: [".jsx", ".js", ".tsx", ".ts", ".json"],
    },
    optimization: {
      splitChunks
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: moduleRegex, // js处理排除node_modules和libs
          use: ["babel-loader"],
        },
        {
          test: /\.tsx?$/,
          exclude: moduleRegex, // js处理排除node_modules和libs
          use: ['babel-loader',tsLoader],
        },
        {
          // 源码就转语法树
          test: /\.css$/,
          exclude: moduleRegex,
          use: getStyleLoaders(true),
        },
        {
          // 三方样式就不转语法树
          test: /\.css$/,
          include: moduleRegex,
          use: getStyleLoaders(false),
        },
        {
          test: /\.less$/, // less只在源码里面写，三方包就用css避免重复打包
          exclude: moduleRegex,
          use: getStyleLoaders(true, {}, "less-loader"),
        },
        {
          test: /\.(jpg|png|gif|jpeg)$/, 
          loader:getUrlLoader(false,"../../")   // 相对此lib输出目录的上两级
        },
        {
          test:/\.svg(\?v=\d+\.\d+\.\d+)?$/,
          loader:getUrlLoader(true,"../../")
        }
      ],
    },
    plugins: [
      new CleanWebpackPlugin(),
      new webpack.DllReferencePlugin({
        manifest: require(path.join(dllPath, "react_manifest.json"))
      }),
      new MiniCssExtractPlugin({
        filename: isDev?"[name].css":"[name].[hash:8].css", 
        chunkFilename: isDev?"[name].css":"[name].[contenthash:8].css",
        ignoreOrder: true 
      }),
      // 分析bundle
      isAnalyzeBundle && new BundleAnalyzerPlugin(),
    ].filter(Boolean),
    performance: {
      maxAssetSize: 2 * 1024 * 1024, //默认值：250000 (bytes)
      maxEntrypointSize: 2 * 1024 * 1024
    },
    stats: isMiniStats?"minimal":"normal" //日志 minimal normal
  };

  return isShowTime ? smp.wrap(config):config;
};
